﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ninject;
using Legazpi.Payroll.BusinessLogic.Services;
using Legazpi.Payroll.BusinessLogic.Services.Interfaces;
using Legazpi.Payroll.DataAccess.DataObjects;
using Web.Codes;
using Web.Utils;

namespace Legazpi.Payroll.Web.Admin
{
    public partial class EmployeeCashAdvance : System.Web.UI.Page
    {
        [Inject]        
        public IEmployeeAdjustmentService _employeeAdjustmentService { get; set; }
        [Inject]
        public IPayrollDateService _payrollDateService { get; set; }

        public bool IsSuccess { get; set; }
        public string NotifyText { get; set; }

        protected double RunningBalance { get; private set; }        
        
        private int _currentEmployeeId;
        public int CurrentEmployeeId
        {
            get
            {
                int id;
                return int.TryParse(EmployeeIdHidden.Value, out id) ? id : 0;
            }
            set
            {
                _currentEmployeeId = value;
                EmployeeIdHidden.Value = _currentEmployeeId.ToString();
            }
        }
        private int _currentEmployeeAdvId;
        public int CurrentEmployeeAdvId
        {
            get
            {
                int id;
                return int.TryParse(EmpAdvIdHidden.Value, out id) ? id : 0;
            }
            set
            {
                _currentEmployeeAdvId = value;
                EmpAdvIdHidden.Value = _currentEmployeeAdvId.ToString();
            }
        }
        private int _currentPaydateId;
        public int CurrentPaydateId
        {
            get
            {
                int id;
                return int.TryParse(PayrollPeriodDdl.SelectedValue.ToString(), out id) ? id : 0;
            }
            set
            {
                _currentPaydateId = value;
                var item = PayrollPeriodDdl.Items.FindByValue(_currentPaydateId.ToString());
                if (item != null)
                {
                    PayrollPeriodDdl.ClearSelection();
                    item.Selected = true;
                }
            }
        }
        private int _currentAdvanceId;
        public int CurrentAdvanceId
        {
            get
            {
                int id;
                return int.TryParse(AdvanceDdl.SelectedValue.ToString(), out id) ? id : 0;
            }
            set
            {
                _currentAdvanceId = value;
                var item = AdvanceDdl.Items.FindByValue(_currentAdvanceId.ToString());
                if (item != null)
                {
                    AdvanceDdl.ClearSelection();
                    item.Selected = true;
                }
            }
        }
        public double CurrentEmployeeCashAdvanceBalance { get; set; }
        
        #region Implementations
        void ResetFigures()
        {
            RunningBalance = 0;            
            //CurrentEmployeeCashAdvanceBalance = _employeeAdjustmentService.GetEmployeeCashAdvanceBalance(CurrentEmployeeId);
        }
        void BindGrid()
        {
            ResetFigures();
            repeater.DataSource = _employeeAdjustmentService.GetAllValidCashAdvanceByEmployeeId(CurrentEmployeeId);
            repeater.DataBind();
        }
        void Delete(int id)
        {
            _employeeAdjustmentService.Delete(id);
            IsSuccess = _employeeAdjustmentService.Save();
            NotifyText = "Successfully Deleted.";
            BindGrid();            
        }

        void Edit(int id)
        {
            var empAdv = _employeeAdjustmentService.GetById(id);
            if (empAdv == null)
                return;

            ObjectToData(empAdv);

            CurrentEmployeeAdvId = empAdv.Id;
            SubmitBtn.Text = "Update";
        }

        void Update(int id)
        {
            var empAdv = _employeeAdjustmentService.GetById(id);
            if (empAdv == null)
            {
                Add();
                return;
            }
            DataToObject(ref empAdv);

            _employeeAdjustmentService.Update(empAdv);
            CurrentEmployeeAdvId = empAdv.Id;

            IsSuccess = _employeeAdjustmentService.Save();
            NotifyText = "Successfully Updated Record.";
        }
        void Add()
        {
            var empAdv = new EmployeeAdjustment();

            DataToObject(ref empAdv);

            _employeeAdjustmentService.Add(empAdv);
            IsSuccess = _employeeAdjustmentService.Save();

            CurrentEmployeeAdvId = empAdv.Id; ;
            NotifyText = "Successfully Added New Record.";
            SubmitBtn.Text = "Update";

        }
        void ClearForm()
        {
            ClearControl(this.Page);
            CurrentEmployeeAdvId = 0;
            SubmitBtn.Text = "Submit";
        }
        void ClearControl(Control ctrl)
        {
            foreach (Control _ctrl in ctrl.Controls)
            {
                if (_ctrl.GetType() == typeof(TextBox))
                {
                    ((TextBox)_ctrl).Text = string.Empty;
                }
                else if (_ctrl.GetType() == typeof(DropDownList))
                {
                    ((DropDownList)_ctrl).SelectedIndex = 0;
                }
                ClearControl(_ctrl);
            }
        }
        void Save()
        {           
            if (CurrentEmployeeAdvId == 0)
                Add();
            else
                Update(CurrentEmployeeAdvId);
        }
        void DataToObject(ref EmployeeAdjustment obj)
        {
            double amount;
            double.TryParse(AmountTxt.Text, out amount);

            obj.EmployeeId = CurrentEmployeeId;
            obj.PayDateId = CurrentPaydateId;
            obj.AdjustmentTypeId = CurrentAdvanceId;
            obj.IsValid = true;
            if (DebitRado.Checked)
            {
                obj.Debit = amount;
                obj.Credit = 0;
            }
            else {
                obj.Debit = 0;
                obj.Credit = amount;
            }
                
        }

        void ObjectToData(EmployeeAdjustment obj)
        {
            CurrentEmployeeAdvId = obj.Id;
            CurrentEmployeeId = obj.EmployeeId;            
            CurrentPaydateId = obj.PayDateId.GetValueOrDefault(0);
            CurrentAdvanceId = obj.AdjustmentTypeId;

            EmployeeName.Text = string.Format("{0} {1}", obj.Employee.FirstName, obj.Employee.LastName);
            

            AmountTxt.Text = obj.Debit > 0 ? obj.Debit.ToString() : obj.Credit.ToString();
            DebitRado.Checked = obj.Debit > 0 && obj.Credit <= 0;
            CreditRado.Checked = obj.Credit > 0 && obj.Debit <= 0;
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                var activePayrollDate = _payrollDateService.GetActivePayroll();
                
                PayrollPeriodDdl.ToPayrollPeriodSelectList(activePayrollDate != null ? activePayrollDate.Id : 0);
                AdvanceDdl.ToAdjustmentCodeSelectList(0);

                BindGrid();
            }
                
        }

        protected void repeater_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            int intTemp = 0;
            if (int.TryParse((string)e.CommandArgument, out intTemp))
            {
                switch (e.CommandName.ToLower())
                {
                    case Constants.Update_Command:
                        Edit(intTemp);
                        break;
                    case Constants.Delete_Command:
                        Delete(intTemp);
                        break;
                }
            }
        }
        protected void repeater_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                var codeLiteral = e.Item.FindControl("CodeLiteral") as Literal;
                var paydateLiteral = e.Item.FindControl("PaydateLiteral") as Literal;
                var debitLiteral = e.Item.FindControl("DebitLiteral") as Literal;
                var creditLiteral = e.Item.FindControl("CreditLiteral") as Literal;
                var balanceLiteral = e.Item.FindControl("BalanceLiteral") as Literal;

                var empAdvItem = ((EmployeeAdjustment)e.Item.DataItem);
                RunningBalance += empAdvItem.Balance;
                codeLiteral.Text = empAdvItem.AdjustmentType.Code;
                debitLiteral.Text = empAdvItem.Debit.ToString("N");
                creditLiteral.Text = empAdvItem.Credit.ToString("N");
                balanceLiteral.Text = RunningBalance.ToString("N");
                paydateLiteral.Text = empAdvItem.PayDate != null ? DateTimeHelper.FormatDateString(empAdvItem.PayDate.Paydate) : string.Empty;
                
            }
        }

        protected void SubmitBtn_Click(object sender, EventArgs e)
        {
            Save();
            if (IsSuccess)
            {
                ClearForm();
                BindGrid();
            }
        }

        protected void CancelBtn_Click(object sender, EventArgs e)
        {
            ClearForm();
        }
        protected void SearchBtn_Click(object sender, EventArgs e)
        {
            if (CurrentEmployeeId > 0)
                BindGrid();
        }
    }
}